﻿using System.ComponentModel;

namespace Utility
{
    /// <summary>
    /// 枚举帮助类
    /// </summary>
    public static class EnumHelper
    {
        /// <summary>
        /// 获取枚举描述值
        /// </summary>
        /// <param name="value">枚举值</param>
        /// <returns></returns>
        public static string GetDescription(this System.Enum value)
        {
            var fi = value.GetType().GetField(value.ToString());
            var attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
            return attributes.Length > 0 ? attributes[0].Description : string.Empty;
        }

        /// <summary>
        /// 根据枚举值获取名称
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string GetName<T>(int value)
        {
            string name = System.Enum.Parse(typeof(T), System.Enum.GetName(typeof(T), value)??string.Empty).ToString() ?? string.Empty;
            return name;
        }

        /// <summary>
        /// 根据描述获取枚举下标
        /// </summary>
        /// <typeparam name="T">枚举</typeparam>
        /// <param name="type">类型</param>
        /// <param name="descriptionValue">描述值</param>
        /// <returns></returns>
        public static int GetValueByDescription<T>(this Type type, string descriptionValue) where T : struct
        {
            var enumValue = 0;
            foreach (var value in System.Enum.GetValues(type))
            {
                var attribute = typeof(T).GetField(value.ToString() ?? string.Empty).GetCustomAttributes(typeof(DescriptionAttribute), false);

                if (attribute != null && ((DescriptionAttribute)attribute[0]).Description == descriptionValue)
                {
                    enumValue = Convert.ToInt32(value);
                }
            }
            return enumValue;
        }

        /// <summary>
        /// 获取枚举所有值,把枚举转换成list
        /// 描述和字符可以相互换
        /// </summary>
        /// <typeparam name="T">枚举类</typeparam>
        /// <param name="type">枚举类</param>
        /// <param name="isTrue">true:描述等于value  false:字符等于value</param>
        /// <returns></returns>
        //public static List<SelectOutPut> GetListAllEnumType<T>(this Type type, bool isTrue = true) where T : struct
        //{
        //    if (!type.IsEnum)
        //        return new List<SelectOutPut>();

        //    var enumValues = System.Enum.GetValues(type);
        //    var list = new List<SelectOutPut>();
        //    foreach (System.Enum value in enumValues)
        //    {
        //        list.Add(new SelectOutPut
        //        {
        //            //Id = value.GetHashCode().ToString(),
        //            value = isTrue == false ? value.GetDescription() : value.ToString(),
        //            label = isTrue == false ? value.ToString() : value.GetDescription(),
        //        });
        //    }
        //    return list;
        //}
    }
}
